package com.nut.spp.service.impl;

import com.nut.spp.common.Result;
import com.nut.spp.config.LoginProperties;
import com.nut.spp.enums.CodeTypeEnum;
import com.nut.spp.redis.RedisClient;
import com.nut.spp.redis.RedisKeys;
import com.nut.spp.service.AuthService;
import com.nut.spp.util.IdUtil;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {

    @Autowired
    private RedisClient redisClient;

    @Resource
    private LoginProperties loginProperties;

    @Override
    public Result<Object> imgCode() {
        // 获取运算的结果
        Captcha captcha = loginProperties.getCaptcha();
        String uuid = IdUtil.uuid();
        String imgCodeKey = RedisKeys.getImgCodeKey(uuid);
        //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == CodeTypeEnum.arithmetic.ordinal() && captchaValue.contains(".")) {
            captchaValue = captchaValue.split("\\.")[0];
        }
        log.info("login_captchaValue=" + captchaValue);
        // 保存
        redisClient.set(imgCodeKey, captchaValue, loginProperties.getExpiration(), TimeUnit.MINUTES);
        // 验证码信息
        Map<String, String> imgResult = new HashMap<>(4);
        imgResult.put("img", captcha.toBase64());
        imgResult.put("uuid", uuid);
        return Result.ok(imgResult);
    }

}
